#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import subprocess
import time
from functools import partial

import requests
from loguru import logger
from retrying import retry

from utils.proxies_tools import get_company_ip_crawler_by_api

subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")  # 消除window下subprocess中文乱码问题
import execjs

execjs.eval("console.log('占位符')")
from utils.db.mysqldb import MysqlDB
from components.config import WFQ_SOURCE_MYSQL_CONFIG
from apps.pdd.pdd.mms import gen_anti_content


class MmsSearch:
    session = requests.session()
    _to_db = None

    def __init__(self, cookies=None):
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            # "anti-content": gen_anti_content(),
            "cache-control": "no-cache",
            "origin": "https://mms.pinduoduo.com",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
        }
        self.session.headers = headers
        if cookies:
            self.session.cookies.update(cookies)

    @property
    def to_db(self):
        if self._to_db is None:
            self._to_db = MysqlDB(
                ip=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_IP"],
                port=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_PORT"],
                db=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_DB"],
                user_name=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_NAME"],
                user_pass=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_PASS"],
            )
        return self._to_db

    @retry(stop_max_attempt_number=5)
    def mall_search(self, mall_name="敖东保健食品官方旗舰店"):
        """
        {"success":true,"errorCode":1000000,"errorMsg":null,"result":{"mallItemList":[{"mallIdEncrypt":"SNhQ1bQmXol_aDBmw2dJdA","mallName":"敖东保健食品官方旗舰店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_20220225e6e4bc82b4ff45318b90bb714d21f471.jpg","displayItemsList":[{"type":1,"text":"已拼: 500万+件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"4年老店","textSize":13,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"退货包运费","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":98}],"goodsItemList":[{"goodsId":336599088376,"picUrl":"https://img.pddpic.com/mms-material-img/2023-01-16/b4bc54fb-b215-408a-b8f2-f5d24195b954.jpeg","price":3390},{"goodsId":336632681252,"picUrl":"https://img.pddpic.com/mms-material-img/2022-03-18/7230f611-fa00-4bf7-9ad5-67a4ca2da2d1.jpeg.a.jpeg","price":2550},{"goodsId":338297654230,"picUrl":"https://img.pddpic.com/mms-material-img/2022-03-23/7d81fb60-b8cf-4e49-bd0e-8f83d6aee18f.jpeg.a.jpeg","price":2859},{"goodsId":375816918636,"picUrl":"https://img.pddpic.com/mms-material-img/2024-11-28/46266086-f200-41a6-9fdf-445106512986.jpeg.a.jpeg","price":979}]},{"mallIdEncrypt":"6IgZzMdKOB2A_zb9hHhcyA","mallName":"敖东保健食品专卖店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_202411114d7308d2904f4210ade7da46c3cafd70.jpg","displayItemsList":[{"type":1,"text":"已拼: 1.4万件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"4年老店","textSize":13,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"坏了包赔","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":98}],"goodsItemList":[{"goodsId":666012794263,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-28/9466b4b7-129d-4d20-95ea-b01b589b53b6.jpeg.a.jpeg","price":57800},{"goodsId":416972269059,"picUrl":"https://img.pddpic.com/mms-material-img/2024-05-10/02c6b268-c1c6-42ab-b5da-5764e9e67981.jpeg","price":25900},{"goodsId":370982897931,"picUrl":"https://img.pddpic.com/mms-material-img/2025-04-25/7f56f9ed-5d67-4b8f-b0bc-e740b087c582.jpeg","price":22500},{"goodsId":369057685025,"picUrl":"https://img.pddpic.com/mms-material-img/2025-01-05/1db6adb7-8db8-4b6f-bb28-1e08e2a5734c.png","price":12000}]},{"mallIdEncrypt":"07gCLcR1na_89q2ue92b7A","mallName":"敖东滋补保健官方旗舰店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_2025030360b0be9c4ca4450e8d64efce7849b079.jpg","displayItemsList":[{"type":1,"text":"已拼: 1.6万件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"7天无理由退货","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":99}],"goodsItemList":[{"goodsId":724103132746,"picUrl":"https://img.pddpic.com/mms-material-img/2025-03-28/126664c9-0fe7-4c74-8433-38174a41be53.jpeg.a.jpeg","price":22200},{"goodsId":760042064052,"picUrl":"https://img.pddpic.com/mms-material-img/2025-06-10/237d24d9-d757-42c7-b9ba-232681a84d1c.jpeg.a.jpeg","price":33600},{"goodsId":722000029140,"picUrl":"https://img.pddpic.com/mms-material-img/2025-03-24/0690961f-cb3d-4f85-a338-7258b4599c3e.jpeg.a.jpeg","price":15900},{"goodsId":625946693675,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-30/0df89905-d915-4ddb-b887-eeee8436ba84.jpeg.a.jpeg","price":9000}]},{"mallIdEncrypt":"qkpS0676fJgimA4vlcsqVw","mallName":"敖东官方旗舰店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_202503229ed1b9b7caeb4a28b5ab57dad3bceba1.jpg","displayItemsList":[{"type":1,"text":"已拼: 8503件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"退货包运费","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":99}],"goodsItemList":[{"goodsId":787476174600,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-30/277fba8d-135e-4aa2-ae3c-4ba75b5e4780.jpeg.a.jpeg","price":26800},{"goodsId":776870327378,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-10/dcbacaa8-8e74-4909-a404-b47eea2ee663.jpeg.a.jpeg","price":20300},{"goodsId":729289937668,"picUrl":"https://img.pddpic.com/mms-material-img/2025-04-08/98b67d40-e8aa-4645-a609-cf1ecd71374b.jpeg.a.jpeg","price":17600},{"goodsId":744926605317,"picUrl":"https://img.pddpic.com/mms-material-img/2025-05-09/f6315403-9e35-4d7d-9260-dbffbfc4f6c2.jpeg.a.jpeg","price":26700}]},{"mallIdEncrypt":"gfGSRYDmz4et4w4mIJQqhw","mallName":"敖东传统滋补旗舰店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_202502101a1e67a6d0584172afcd0351c4612362.jpg","displayItemsList":[{"type":1,"text":"已拼: 3.1万件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"7天无理由退货","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":99}],"goodsItemList":[{"goodsId":777522520503,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-11/a54e3081-80d2-4596-945f-8e84fa39f487.jpeg.a.jpeg","price":251760},{"goodsId":776324280011,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-09/d32fe4c2-418c-4158-ae46-cda2467b8ffc.jpeg.a.jpeg","price":61500},{"goodsId":776287394082,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-09/f06b782d-a456-4edb-b312-860fd0fb11a1.jpeg.a.jpeg","price":106680},{"goodsId":776826640813,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-10/6b33d521-14d8-4e4c-bb4d-fb59fe1bd3ec.jpeg.a.jpeg","price":44800}]},{"mallIdEncrypt":"piX6OReskvJbbOsXZfR-3Q","mallName":"敖东AD大药房旗舰店","mallLogo":"https://img.pddpic.com/goods_mms/2023-11-16/1fb50afb-b186-4ca5-84ef-6d2ab95aa05d_suffix.png","displayItemsList":[{"type":1,"text":"已拼: 500万+件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"退货包运费","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":99}],"goodsItemList":[{"goodsId":787908859275,"picUrl":"https://img.pddpic.com/mms-material-img/2025-02-17/3e0583ea-bd9e-43f0-aecd-ec787dee8695.jpeg","price":9690},{"goodsId":629988956322,"picUrl":"https://img.pddpic.com/mms-material-img/2025-04-30/2984d05c-a8ce-433c-9c66-ebe3183dcc3f.jpeg","price":27300},{"goodsId":580594545313,"picUrl":"https://img.pddpic.com/mms-material-img/2025-06-09/06bada27-8bcb-4c89-918d-dcb512160f7e.jpeg.a.jpeg","price":29800},{"goodsId":561438674216,"picUrl":"https://img.pddpic.com/mms-material-img/2024-03-09/24b65397-2740-4f80-9969-fd006b0d6832.jpeg","price":29800}]},{"mallIdEncrypt":"L-f6xKZJ-O_jNQrtc7XdHQ","mallName":"敖东健康旗舰店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_20220721a6e8bc8d232844e186220bf5b921eae8.jpg","displayItemsList":[{"type":1,"text":"已拼: 6.7万件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"4年老店","textSize":13,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"7天无理由退货","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":98}],"goodsItemList":[{"goodsId":447971622295,"picUrl":"https://img.pddpic.com/mms-material-img/2025-01-21/dd0c5c7d-9dca-4c0b-b297-eaf9c93e4ad5.jpeg","price":5990},{"goodsId":480086396312,"picUrl":"https://img.pddpic.com/mms-material-img/2024-09-23/310d0ed4-8677-40e4-9905-89135c1af2da.jpeg","price":1690},{"goodsId":696481851744,"picUrl":"https://img.pddpic.com/mms-material-img/2025-01-13/bbb26703-77b8-4681-838c-9f5ce778d4f2.png","price":4900}]},{"mallIdEncrypt":"Rv57DWcjgXvzf83qmOgrhg","mallName":"敖东大药房旗舰店","mallLogo":"https://t00img.yangkeduo.com/goods/images/2019-06-13/bdd52977-48d2-4a51-894e-291fda0f199b.jpg","displayItemsList":[{"type":1,"text":"已拼: 500万+件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"7年老店","textSize":13,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"退货包运费","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":98}],"goodsItemList":[{"goodsId":46051683978,"picUrl":"https://img.pddpic.com/mms-material-img/2025-02-05/e710a890-6f11-4d9f-9ea0-1bbc925c6d19.jpeg","price":24700},{"goodsId":701966767942,"picUrl":"https://img.pddpic.com/mms-material-img/2025-02-11/3812b516-871b-4d44-913b-054bf8c1fd1e.jpeg","price":76800},{"goodsId":787861875577,"picUrl":"https://img.pddpic.com/mms-material-img/2021-08-19/3d02788e-4c86-4c76-8be2-d7cd3718fe57.jpeg.a.jpeg","price":8800},{"goodsId":787861698458,"picUrl":"https://img.pddpic.com/mms-material-img/2021-08-19/3d02788e-4c86-4c76-8be2-d7cd3718fe57.jpeg.a.jpeg","price":8800}]},{"mallIdEncrypt":"pQGSSKTe01BEhC6qNquo8g","mallName":"敖东苏茂专卖店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_20241009dde399ca8aad4e25b6adc76b0b2fc10a.jpg","displayItemsList":[{"type":1,"text":"已拼: 817件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"退货包运费","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":99}],"goodsItemList":[{"goodsId":753554755859,"picUrl":"https://img.pddpic.com/mms-material-img/2025-05-27/c97bf80e-37c1-462c-aaca-1055dfa93c02.jpeg.a.jpeg","price":35800},{"goodsId":743381673276,"picUrl":"https://img.pddpic.com/mms-material-img/2025-05-06/c34dfb16-fe52-460a-b9dd-31c3bb1deb8a.jpeg.a.jpeg","price":24591},{"goodsId":743322937087,"picUrl":"https://img.pddpic.com/mms-material-img/2025-05-06/a6ff7e30-df73-424a-8844-4335e43c5fb9.jpeg.a.jpeg","price":16800},{"goodsId":743318174366,"picUrl":"https://img.pddpic.com/mms-material-img/2025-05-06/5a69fcc7-4a27-4396-bae7-7dcc674787e3.jpeg","price":11800}]},{"mallIdEncrypt":"YlUsM4LK9vn8jN8N5XHT8g","mallName":"敖东世医门专卖店","mallLogo":"http://t16img.yangkeduo.com/pdd_ims/mainObject/v1/pub_202501200f05438e05054898814b65a5c0362a6a.jpg","displayItemsList":[{"type":1,"text":"已拼: 1.4万件","textSize":12,"textColor":"#9B9B9B","backgroundColor":null,"url":null,"height":null,"width":null,"priority":100},{"type":1,"text":"7天无理由退货","textSize":12,"textColor":"#E02E24","backgroundColor":"#FDEFEE","url":null,"height":null,"width":null,"priority":99}],"goodsItemList":[{"goodsId":780093293920,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-15/7cc6f64b-cc33-4523-ac62-0415332d7b61.jpeg.a.jpeg","price":371760},{"goodsId":780123394915,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-15/574dca8c-c205-4751-88d1-5d320dcdbfee.jpeg.a.jpeg","price":251760},{"goodsId":780604315956,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-16/402c3fa2-4a43-4679-a3dd-37316b26e5b1.jpeg.a.jpeg","price":62000},{"goodsId":780999073011,"picUrl":"https://img.pddpic.com/mms-material-img/2025-07-17/265cc370-829b-477b-a16f-5c5a5b7bfe2a.jpeg.a.jpeg","price":44800}]}],"rn":null}}
        """
        logger.info("开始搜索店铺: {}".format(mall_name))
        url = "https://mms.pinduoduo.com/pifa/bapp/order/mallSearch"
        data = {"size": 10, "page": 1, "mallName": mall_name, "sort": 0}
        self.session.headers.update(
            {
                "anti-content": gen_anti_content(),
            }
        )
        response = self.session.post(
            url, json=data, proxies=self.get_proxies(), headers=self.session.headers, timeout=10
        )
        resp = response.json()
        logger.debug(f"店铺搜索结果: {resp}")
        error_code = resp.get("error_code") or resp.get("errorCode")
        if error_code != 1000000:
            raise Exception(f"操作太过频繁，请稍后再试！：{resp}")
        mall_item_list = resp.get("result", {}).get("mallItemList", [])
        for item in mall_item_list:
            if item["mallName"] == mall_name:
                return item
        else:
            logger.warning("未找到店铺: {}".format(mall_name))
        return None

    def mall_search_with_save(self, mall_name, mall_id):
        item = self.mall_search(mall_name)
        if item:
            self.to_db.add_smart(
                "zm_pdd_mall_id",
                {
                    "mall_id": mall_id,
                    "is_searched": 1,
                    "mall_id_encrypt": item["mallIdEncrypt"],
                },
                update_columns=["is_searched", "mall_id_encrypt"],
            )
        else:
            self.to_db.add_smart(
                "zm_pdd_mall_id",
                {
                    "mall_id": mall_id,
                    "is_searched": 0,
                },
                update_columns=["is_searched"],
            )
        return item

    def get_proxies(self):
        tunnel = "k574.kdltps.com:15818"
        # 用户名密码方式
        username = "t18981766485155"
        password = "yasfhbbt"
        proxies = {
            "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
            "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
        }
        proxies = get_company_ip_crawler_by_api()
        print(proxies)
        return proxies

    def auto_fill_mall_id_encrypt(self, size=100):
        sql = fr"""
        select mall_id, shop_name
        from zm_pdd_mall_id
        where zm_certificate_flag = 1
          and certificate_flag is null
          and shop_name not like '%\_%'
          and is_searched is null
          limit {size}
        """
        datas = self.to_db.find(sql, to_json=True)
        for data in datas:
            mall_id = data["mall_id"]
            mall_name = data["shop_name"]
            try:
                self.mall_search_with_save(mall_name, mall_id)
                time.sleep(random.uniform(10, 20))
            except Exception as e:
                logger.error(f"{mall_id} {mall_name} {e}")
                time.sleep(60 * 10)


if __name__ == "__main__":
    # MmsSearch().mall_search_with_save('翠芭农资', 102794911)
    MmsSearch(
        {
            # "PASS_ID": "1-/ibmmkUhVhZDhUVCn4ZslHKaufKk3Uz/+exyfKKJhGFl5x2tJukK17D/l76tuiGOkvZLi3ig/KKwxhOMvlwanA_674110087_169809275",
            # "api_uid": "CiL0XWiMe/W1mQCRrsw6Ag==",
            # "rckk": "0KnmGQbIBxM965CND9n283P3xPfBzfER",
            # "_bee": "0KnmGQbIBxM965CND9n283P3xPfBzfER",
            # "ru1k": "f4f488d4-f4cc-4579-99c2-c8af6fe16c21",
            # "_f77": "f4f488d4-f4cc-4579-99c2-c8af6fe16c21",
            # "ru2k": "15ca269b-5d9d-44dd-852d-646c2225b362",
            # "_a42": "15ca269b-5d9d-44dd-852d-646c2225b362",
            # "_nano_fp": "Xpmyn09qnqT8n5XonT_L1ZTsVk3FAOQe3KGKmYMU",
            # "PASS_ID": "1-KI16fb/N6h/M412eorwf+WlPPlCDuUUs7h6pdK+OX6gWy4y1wJYb1Ycxc4PiSVv0odkYv7r0Fj/AiwNIv16eEQ_704785187_160760091",
            # "webp": "true",
            # "mms_b84d1838": "3616,3523,3660,3614,3599,3603,3605,3621,3622,3588,3254,3532,3474,3475,3477,3479,3482,1202,1203,1204,1205,3417",
            # "x-visit-time": "1754040405119",
            # "JSESSIONID": "EFA6C3C235F07CB65A6C16C6E729CC47",
            # "mms-mobile-captcha-cookie-token": "bWPhfqWWfegnyshNo9CReA1a37a8e9f86e1f84d",
            # "CAVA_USER": "eyJpZCI6MTYwNzYwMDkxLCJtYWxsSWQiOjcwNDc4NTE4N30=",
        }
    ).auto_fill_mall_id_encrypt(10000)
